package com;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class Mysource{
    private boolean flag= true;
    private AtomicInteger atomicInteger = new AtomicInteger();
     private  BlockingQueue<String> blockingQueue= null;

    public Mysource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    /**
     * 把数据添加到 阻塞队列中
     */
    public void  myProd(){
        String data = null;
        while(flag)
        {
            try {
                data = atomicInteger.getAndAdd(1)+"";
                boolean offer = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
                if(offer){
                    System.out.println(Thread.currentThread().getName()+"添加成功"+data);
                }else {
                    System.out.println(Thread.currentThread().getName()+"添加失败"+data);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
    public  void   myconsumer(){
        String data =null;
        while (flag){
            try {
                data = blockingQueue.poll(2, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class BlockingQeueuTest {
    public static void main(String[] args) {
       //   testBlockingQueue();
    }

    private static void testBlockingQueue() {
        ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(8);
        String [][] str = new String[3][];
        str[0] = new String[]{};

        new Thread(()->{
            for (int i = 0; i <100; i++) {
                try {
                    blockingQueue.put(1);
                    System.out.println("线程1我放进去"+i+"个");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程1").start();
        new Thread(()->{
            for (int i = 0; i <100; i++) {
                try {
                    blockingQueue.take();
                    System.out.println("线程2我拿出来一个");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程2").start();
        new Thread(()->{
            for (int i = 0; i <100; i++) {
                try {
                    blockingQueue.take();
                    System.out.println("线程3我拿出来一个");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程3").start();
    }
}
